package com.example.springbootthreadexamples.interceptor;

import com.example.springbootthreadexamples.thread.UserContext;
import com.example.springbootthreadexamples.thread.UserContextInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author LanWP
 * @date 2024-08-02
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String token = request.getHeader("token");
            UserContextInfo userContextInfo = new UserContextInfo("123456", "张三", new Date(), LocalDateTime.now());
            UserContext.setUserContext(userContextInfo);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
